import {
    Card,
    Breadcrumb,
    Form,
    Button,
    Radio,
    Input,
    Upload,
    Space,
    Select,
    message
  } from 'antd'
  import { PlusOutlined } from '@ant-design/icons'
  import { Link, useNavigate, useSearchParams } from 'react-router-dom'
  import './index.scss'
  import ReactQuill from 'react-quill'
  import 'react-quill/dist/quill.snow.css'
import {useEffect, useState } from 'react'
import { createArticleAPI, getArticleById, updateArticleById} from '@/apis/article'
import { useChannel } from '@/hook/useChannel'
  const { Option } = Select
  
  const Publish = () => {
    const [imageList , setImageList] = useState([])
    const [imageType , setImageType] = useState(0)
    const navigate = useNavigate()
    const {channelList} = useChannel()

    const onFinish = async(formValue) =>{

        if(imageType !== imageList.length) return message.warning('图片数量不匹配')

        console.log(formValue)
        const {title , content , channel_id} = formValue
        // 按照接口文档的格式处理收集到的表单数据
        const reqData = {
            title,
            content,
            cover: {
                type: imageType,
                images: imageList.map(item => {
                  if(item.response){
                    return item.response.data.url
                  }else {
                    return item.url
                  }
                })
            },
            channel_id
        }
        // 调用接口提交
        if(articleId){
          await updateArticleById({...reqData,id:articleId})
        }
        else 
          await createArticleAPI(reqData)
        navigate(`/article`)

    }
    // onUploadChange在图片上传过程中会不断执行
    const onUploadChange = (data)=>{
        console.log(data)
        setImageList(data.fileList)
    }

    const onTypeChange = (data)=>{
        // data.targe.value表示封面类型
        setImageType(data.target.value)
    }

    // 异步渲染回填数据
    const [searchParams] = useSearchParams()
    const articleId = searchParams.get('id') // 获取路由上的id数据
    // 获取实例 
    const [form] = Form.useForm()
  
    useEffect(()=>{
      // 获取数据
      async function getArticleDetail() {
        const res = await getArticleById(articleId)
        const data = res.data
        const cover = data.cover
        form.setFieldsValue({
          ...data,
          type:cover.type
        })
        setImageType(cover.type)
        setImageList(cover.images.map(url=>{
          return{url}
        }))
      }
      if(articleId) getArticleDetail()
      // 调用实例方法 完成回填
    },[articleId,form])
    
    return (
      <div className="publish">
        <Card
          title={
            <Breadcrumb separator=">">
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>{articleId ? '编辑文章':'发布文章'}</Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ type: 0 }}
            onFinish={onFinish}
            form={form}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[{ required: true, message: '请输入文章标题' }]}
            >
              <Input placeholder="请输入文章标题" style={{ width: 400 }} />
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[{ required: true, message: '请选择文章频道' }]}
            >
              <Select placeholder="请选择文章频道" style={{ width: 400 }}>
                {channelList.map(item => <Option key={item.id} value={item.id}>{item.name}</Option>)}
              </Select>
            </Form.Item>
  
            <Form.Item label="封面">
              <Form.Item name="type" onChange={onTypeChange}>
                <Radio.Group>
                  <Radio value={1}>单图</Radio>
                  <Radio value={3}>三图</Radio>
                  <Radio value={0}>无图</Radio>
                </Radio.Group>
              </Form.Item>
              {/*
                listType:决定选择文件框的外观模式
                showUploadList:控制显示上传列表
              */}
              {imageType > 0 && <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                action="http://geek.itheima.net/v1_0/upload"
                fileList={imageList}
                onChange={onUploadChange}
                maxCount={imageType}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>}
            </Form.Item>
            <Form.Item
              label="内容"
              name="content"
              rules={[{ required: true, message: '请输入文章内容' }]}
            >
                {/* 富文本编辑器 】*/}
            <ReactQuill
                className="publish-quill"
                theme="snow"
                placeholder="请输入文章内容"
            />
            </Form.Item>
  
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button size="large" type="primary" htmlType="submit" >
                  {articleId? '修改文章': '发布文章'}
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
  
  export default Publish